//
//  GroupInfoVC.m
//  NtoccShipper
//
//  Created by mac on 2019/11/19.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "GroupInfoVC.h"
#import "GroupInfoCell.h"
#import "DriverListVC.h"
#import "GroupInfoModel.h"
#import "MyInPutAlertView.h"
#import "DriverListModel.h"
#import "GroupInfoCellNew.h"

@interface GroupInfoVC ()<UITableViewDelegate,UITableViewDataSource>

//@property (nonatomic,strong) AppectGroupCell *appectGroupCell;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) GroupInfoCellNew *groupInfoCellNew;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (weak, nonatomic) IBOutlet UILabel *labName;
@property (weak, nonatomic) IBOutlet UIButton *btnTitleName;
@property (weak, nonatomic) IBOutlet UIView *viewTop;
@property (weak, nonatomic) IBOutlet UIButton *btnAddDriver;
@property (nonatomic,copy) NSString *driverCodes;
@end

@implementation GroupInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:@"分组信息"];
    [self setBackLeftButton:@""];
    
    self.labName.textColor = [UIColor cjSubheadTextColor];
    self.groupInfoCellNew = [[GroupInfoCellNew alloc]initWithFlex:nil reuseIdentifier:nil];

    [self.btnTitleName setTitleColor:[UIColor cjMainTextColor] forState:UIControlStateNormal];
    self.btnAddDriver.backgroundColor = [UIColor cjMainColor];
    
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
    
    [self.btnTitleName setTitle:self.strTitle forState:UIControlStateNormal];
    [self.btnTitleName setTitleColor:[UIColor cjMainColorText] forState:UIControlStateNormal];
        [self.btnTitleName setTitleColor:[UIColor cjMainColorText] forState:UIControlStateSelected];
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/acceptVehicle",CJBaseUrl);
    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"teamCode":self.strCode
    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);
        ws.driverCodes = responseObject[@"driverCodes"];
        NSDictionary *dic = responseObject[@"page"];
        NSArray *list = dic[@"records"];
        NSString *total = CJStringWithFormat(@"%@",dic[@"total"]);
//        if (list.count > 0) {
            if ([ws.refreshType isEqualToString:@"down"]) {
                [ws.modelArray removeAllObjects];
            }
            NSError * error ;
            NSArray *arr = [GroupInfoModel arrayOfModelsFromDictionaries:list error:&error];
            [ws.modelArray addObjectsFromArray:arr];

            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];
            
            if (ws.modelArray.count == total.intValue) {
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }
//        }else{

//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }

        [ws.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 120;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([CJControl getUIWithNew]) {
        static NSString *identifier = @"GroupInfoCellNew";
        GroupInfoCellNew *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
           cell = [[GroupInfoCellNew alloc] initWithFlex:nil reuseIdentifier:identifier];
           cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        GroupInfoModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];
        WS(ws);
        cell.blockDelete = ^(id anyObject) {
            [ws btnDeleteDriverAction:model];
        };
      
        return cell;
    }else{
        static NSString *identifier = @"GroupInfoCell";
        GroupInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
        //        cell = [[AppectGroupCell alloc] initWithFlex:nil reuseIdentifier:identifier];
        //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell = [[[NSBundle mainBundle] loadNibNamed:@"GroupInfoCell" owner:nil options:nil] firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
        GroupInfoModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];
        WS(ws);
        cell.blockDelete = ^(id anyObject) {
            [ws btnDeleteDriverAction:model];
        };
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

- (void)btnDeleteDriverAction:(GroupInfoModel *)model{

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/acceptVehicle",CJBaseUrl);
    NSDictionary *dicPar = @{@"codes":model.code
                            
    };
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"删除提醒" strContent:CJStringWithFormat(@"确定要删除%@吗？",model.driverName) ClickOnSure:^(NSString * _Nonnull strSure) {

        WS(ws);
         [[HDNetworking sharedHDNetworking] DELETE:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
             
             DLog(@"++++++++%@",responseObject);
             [ws.tableView.mj_header beginRefreshing];
             
         } failure:^(NSError * _Nonnull error) {
             DLog(@"++++++++%@",error);
             
         }];
    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        DLog(@"-=-=-=-=");
    }];
    
    alert.center = KEYWINDOW.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss=YES;
    [alertView show];

}

- (IBAction)btnAddDriverAction:(id)sender {
    
    WS(ws);
    DriverListVC *vc = [DriverListVC new];
    vc.blockSeletArr = ^(id anyObject) {
        
        DLog(@"====== %@",anyObject);
        NSArray *list = (NSArray *)anyObject;
        
        __block NSString *strName = @"";
        __block NSString *codes = @"";
        [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            DriverListModel *model= obj;
            if (idx == 0) {
                strName = model.name;
                codes = model.partyCode;
            }else{
                strName = CJStringWithFormat(@"%@,%@",strName,model.name);
                codes = CJStringWithFormat(@"%@,%@",codes,model.partyCode);
            }
            
        }];
        
        if (IsStrEmpty(self.driverCodes) || IsNilOrNull(self.driverCodes)) {
            
        }else{
            codes = CJStringWithFormat(@"%@,%@",codes,self.driverCodes);
        }
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/vehicleTeam/shipment",CJBaseUrl);
        NSDictionary *dicPar = @{@"teamCode":ws.strCode,
                                 @"name":ws.strTitle,
                                 @"driverCodes":codes
        };
        
       
        [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            
            DLog(@"++++++++%@",responseObject);
            [ws.tableView.mj_header beginRefreshing];
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            
        }];
    };
    
    [self pushVc:vc];
}
- (IBAction)btnChangeName:(UIButton *)sender {
    
    MyInPutAlertView *alert = [[MyInPutAlertView alloc]initWithTitle:@"修改承运分组名称" Placeholder:@"请填写承运分组名称" ClickOnSure:^(NSString *strInPut) {
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/vehicleTeam/shipment",CJBaseUrl);
        NSDictionary *dicPar = @{@"teamCode":self.strCode,
                                 @"name":strInPut,
                                 @"driverCodes":self.driverCodes
        };
        
        WS(ws);
        [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
//            DLog(@"++++++++%@",responseObject);
            [ws.btnTitleName setTitle:strInPut forState:UIControlStateNormal];
            ws.strTitle = strInPut;
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
        }];
        
    } ClickOnCancle:^(NSString *strCancle) {
        
    }];
    
    alert.center = KEYWINDOW.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss=YES;
    [alertView show];
    
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + self.viewTop.height + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight  - self.viewTop.height - self.btnAddDriver.height - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end

